/*
Copyright (C) 2016  Marien Raat

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "aiManager.h"
#include "config.h"

#include <iostream>

void AIManager::initialize(Car *cars, bool *playersConnected,
                           int maxCars, Ball *ball)
{
    this->cars = cars;
    this->playersConnected = playersConnected;
    this->maxCars = maxCars;
    this->ball = ball;
    aiToMakeEven.setBall(ball);
}

void AIManager::update()
{
    int blue = 0, red = 0;
    for (int i = 0; i < maxCars; i++)
        if (playersConnected[i]) {
            if (i % 2)
                blue++;
            else
                red++;
        }

    if (blue != red) {
        for (int i = blue > red ? 0 : 1; i < maxCars; i += 2)
            if (!playersConnected[i]) {
                aiIndex = i;
                break;
            }

        if (!cars[aiIndex].getInWorld()) {
            cars[aiIndex].setInWorld(true);
            cars[aiIndex].setPosition(
                sf::Vector2f((aiIndex % 2 ? FIELD_SIZE.x - 50 : 50),
                             FIELD_SIZE.y / 2));
            if (aiIndex % 2) cars[aiIndex].setRotation(180);
        }

        aiToMakeEven.setCar(cars + aiIndex);
        aiToMakeEven.update();
    }

    for (int i = 0; i < maxCars; i++)
        if (i != aiIndex && !playersConnected[i])
            cars[i].setInWorld(false);

    aiIndex = -1;
}
